package com.niit.project.service.impl;

import com.niit.project.dao.GoodsDao;
import com.niit.project.dao.impl.GoodsDaoImpl;
import com.niit.project.entity.Goods;
import com.niit.project.entity.Page;
import com.niit.project.service.GoodsService;
import com.niit.project.utils.Dbutils;

import java.util.List;

public class GoodsServiceImpl implements GoodsService {
    private GoodsDao goodsDao = new GoodsDaoImpl();

    @Override
    public List<Goods> showAllByPage(Page page) {
        List<Goods> goods =  null;
        try {
            Dbutils.begin();
            long count = goodsDao.selectCount();
            page.setTotalCounts((int)count);
            goods = goodsDao.selectAll(page);
            Dbutils.commit();
        } catch (Exception e) {
            Dbutils.rollback();
            throw new RuntimeException(e);
        }
        return goods;
    }

    @Override
    public int deleteGoods(String goodname) {
        int result = 0;
        try {
            //开启事务
            Dbutils.begin();
            //调用Dao层的delete方法，将选中的商品从数据库中删除
            result =goodsDao.delete(goodname);
            //提交事务
            Dbutils.commit();
        } catch (Exception e) {
            //事务回滚
            Dbutils.rollback();
            throw new RuntimeException(e);
        }

        return result;

    }

    @Override
    public int addGoods(Goods Goods) {
        int result = 0;
        try {
            Dbutils.begin();
            result = goodsDao.insert(Goods);
            System.out.println("公共模块已添加");
            Dbutils.commit();
        } catch (Exception e) {
            Dbutils.rollback();
            throw new RuntimeException(e);
        }
        return result;
    }

    @Override
    public Goods selectGoodsById(int id) {
        Goods goods = null;
        try {
            Dbutils.begin();
            goods = goodsDao.select(id);
            Dbutils.commit();
        } catch (Exception e) {
            Dbutils.rollback();
            throw new RuntimeException(e);
        }
        return goods;
    }

    @Override
    public int modifyGoods(Goods Goods) {
        return 0;
    }

    @Override
    public List<Goods> showSearch(Page page) {
        List<Goods> goods =  null;
        try {
            Dbutils.begin();
            long count = goodsDao.selectCount();
            page.setTotalCounts((int)count);
            goods = goodsDao.selectAll(page);
            Dbutils.commit();
        } catch (Exception e) {
            Dbutils.rollback();
            throw new RuntimeException(e);
        }
        return goods;
    }
}
